from django.shortcuts import render
from django.http import HttpResponse, HttpRequest
from .models import DeviceData
import json
from .utils import create_datetime
import logging
import datetime
import math

LOG_FORMAT = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'

# logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)


def index(request):
    return render(request, 'main/index.html', {})


def data_request(request: HttpRequest, web_data_len=0, **kwargs):

    dts = str(request.GET.get('cdt', '2020/3/26/23/59/59/0'))
    logging.info(dts)
    cdt = create_datetime(dts)
    logging.info(cdt)
    data = DeviceData.objects.filter(datetime__gt=cdt)
    count = len(data)
    logging.info(count)
    logging.info("web_data_len: " + str(web_data_len))

    if web_data_len > count:
        web_data_len = count
    elif web_data_len == 0:
        return HttpResponse(json.dumps(None))
    logging.info("web_data_len: " + str(web_data_len))
    data = data[count - web_data_len:]
    data_li = list()
    logging.info("data len: " + str(len(data)))
    for i in data:
        data_li.append(i.to_dict)
    return HttpResponse(json.dumps(data_li))


def all_data(request: HttpRequest):
    all_data_ = DeviceData.objects.all()
    data_li = list()
    logging.info("data len: " + str(len(all_data_)))
    for i in all_data_:
        data_li.append(i.to_dict2)
    return HttpResponse(json.dumps(data_li))


def data_predict(request):
    now = datetime.datetime.now()
    pdt = list()
    for i in range(200):
        now += datetime.timedelta(seconds=2)
        ctime = {
            'year': now.year,
            'month': now.month,
            'day': now.day,
            'hour': now.hour,
            'minute': now.minute,
            'second': now.second,
            'microsecond': now.microsecond
        }
        d = dict(predictValue=math.sin(i / 100 * math.pi), datetime=ctime)
        pdt.append(d)

    return HttpResponse(json.dumps(pdt))


def data_fit(request):
    from predict.fit import fit
    return HttpResponse(fit())


def data_mul_fit(request):
    from predict.fit import mul_fit
    image_path = mul_fit()
    image = open(image_path, 'rb').read()
    return HttpResponse(image, content_type="image/jpg")


def notifications(request):
    pass
